package com.library.dao;

import com.library.entity.Libcard;
import com.library.util.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Date;
import java.sql.SQLException;

public class LibcardDao {
    private final QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());

    // 查询借书证
    public Libcard getBySno(String sno) {
        String sql = "SELECT sno, sname, type, collage, major, birth, originPlace, cardStatus AS cardType, times, cardNo FROM libcard WHERE sno = ? ORDER BY cardStatus='正常' DESC, cardNo DESC LIMIT 1";
        try {
            return queryRunner.query(sql, new BeanHandler<>(Libcard.class), sno);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 更新借书证状态
    public void updateStatus(String sno, String status) {
        String sql = "UPDATE libcard SET cardStatus = ? WHERE sno = ?";
        try {
            queryRunner.update(sql, status, sno);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    // 新办借书证
    public void insertLibcard(String cardNo, String sno, String sname, String type, String collage, String major, Date birth, String originPlace) {
        String sql = "INSERT INTO libcard(cardNo, sno, sname, type, collage, major, birth, originPlace, cardStatus, times) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '正常', 0)";
        try {
            queryRunner.update(sql, cardNo, sno, sname, type, collage, major, birth, originPlace);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    // 插入借书证操作记录
    public void insertCardrec(String sno, String cardNo, String opType) {
        String sql = "INSERT INTO cardrec(sno, originCardNo, opType) VALUES (?, ?, ?)";
        try {
            queryRunner.update(sql, sno, cardNo, opType);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    // 通过cardNo更新借书证状态
    public void updateStatusByCardNo(String cardNo, String status) {
        String sql = "UPDATE libcard SET cardStatus = ? WHERE cardNo = ?";
        try {
            queryRunner.update(sql, status, cardNo);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
} 